package com.whq.wechatpay;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.naming.NoNameCoder;
import com.thoughtworks.xstream.io.xml.Xpp3Driver;
import com.whq.wechat.Constant;
import com.whq.wechat.WechatPayOrderVo;
import com.whq.wechat.WeiChatPreAppOrder;
import com.whq.wechat.utils.QRCodeUtil;
import com.whq.wechat.utils.Signature;
import com.whq.wechat.utils.WechatUrl;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by lenovo on 2018/4/11.
 */
@Service
public class WechatPayServiceImpl implements WechatPayService{
    Logger logger = LoggerFactory.getLogger(WechatPayServiceImpl.class);

    @Override
    public String makeWechatPay(WechatPayOrderVo chargeOrder) {

        logger.info("进去系统统一下单接口");
        String code_url = null;
        try {
            //生成签名参数组装开始
            // 签名随机字符串，由于微信里面的坑太多，所以我们所有的签名字符串和时间戳最好公用，不然真的会蒙圈的
            String weiPaySignStr = WechatUrl.getRandomStringByLength(20);
            // 签名用时间戳 秒
            String timestamp = (System.currentTimeMillis()/1000) + "";
            // 统一下单签名参数哈希表
            // 统一下单的body,就是商品详情，要是传中文记得newString(body.getBytes("ISO8859-1"))，不然JS签名失败，
            // 但是即使这样,支付成功后微信给你发的支付凭证中商品详情还是乱码显示，所以传英文吧，这坑懒得去填
            String body = "langdeng WeChat Order Pay";
            Map<String, Object> prepaySignParam = new HashMap<String, Object>();
            prepaySignParam.put("appid",  Constant.APPID);//替换
            prepaySignParam.put("mch_id",  Constant.MCHID);//替换
            prepaySignParam.put("body", body);//商品描述
            prepaySignParam.put("nonce_str", weiPaySignStr);//随机字符串
            // 微信异步通知地址，在这里处理后续订单逻辑
            prepaySignParam.put("notify_url",
                    Constant.DOMAIN+"/api/v1/wechat/weipayCallBack");
            logger.info(Constant.DOMAIN+"/api/v1/wechat/weipayCallBack");//替换
            prepaySignParam.put("out_trade_no", chargeOrder.getOrderNo()); //获取系统订单编号
            prepaySignParam.put("spbill_create_ip", "123.12.12.123");// 用户IP地址
            //测试先改为0.01
            // 单位分
//            prepaySignParam.put("total_fee",chargeOrder.getTotal().multiply(new BigDecimal(100)));
            prepaySignParam.put("total_fee","1");
            //正式
            // prepaySignParam.put("total_fee", chargeOrder.getTotal().multiply(new BigDecimal(100)).intValue());
            prepaySignParam.put("trade_type", "NATIVE");
            //生成签名参数组装结束
            //生成签名开始
            String sign = Signature.getSign(prepaySignParam);




            // 构造微信预支付订单 开始
            WeiChatPreAppOrder weiChatPreOrder = new WeiChatPreAppOrder();
            weiChatPreOrder.setAppid(Constant.APPID);
            weiChatPreOrder.setMch_id(Constant.MCHID);
            weiChatPreOrder.setBody(body);
            weiChatPreOrder.setNonce_str(weiPaySignStr);
            weiChatPreOrder.setNotify_url(Constant.DOMAIN+"/api/v1/wechat/weipayCallBack");
            weiChatPreOrder.setOut_trade_no(chargeOrder.getOrderNo());// 系统订单号
            weiChatPreOrder.setSpbill_create_ip("123.12.12.123");
            //测试先改为0.01
            weiChatPreOrder.setTotal_fee(1);
            //正式
            //weiChatPreOrder.setTotal_fee(chargeOrder.getTotal().multiply(new BigDecimal(100)).intValue());
            weiChatPreOrder.setTrade_type("NATIVE");
            // 计算统一下单签名参数计算预支付订单的MD5签名
            logger.info("微信的key"+ Constant.WECHAT_KEY);

            //   加密签名
            weiChatPreOrder.setSign(sign);
            // 生成XML订单
            XStream stream = new XStream(new Xpp3Driver(new NoNameCoder()));
            stream.processAnnotations(weiChatPreOrder.getClass());
            String xmlOrder = stream.toXML(weiChatPreOrder);
            logger.info("统一下单接口的xml" + xmlOrder);
            //构造微信预支付订单结束

            // 通过微信下单接口获取code_url

            code_url = WechatUrl.getCodeUrl(xmlOrder);
            logger.info("统一下单接口的code_url"+code_url);

            String codeImg = createCodeImg(code_url);
            logger.info("统一下单接口的code_url"+codeImg);
        } catch (Exception e) {
            logger.info("app获取支付所需参数错误"+e.getMessage());
        }
        return code_url;
    }


    @Override
    public String createCodeImg(String url) throws Exception {
        String codeUrl = QRCodeUtil.encode(url, "", Constant.CODE_IMG_PATH, false);
        return Constant.IMG_URL+codeUrl;
    }
}
